﻿using Jayden.Dll.Web.Controls;
using Jayden.Dll.Web.HtmlControls;
using Jayden.Sc2;
using Jayden.Dll.Sc2.Descriptions;
using Jayden.Dll.Sc2;
using System.Collections.Generic;
using Jayden.Dll.Web.Enums;
using System.Text.RegularExpressions;
using Jayden.Dll.Core.Exceptions;

namespace Jayden.Site.Sc2.Dll
{
	public class Sc2PageHtml : PageHtml
	{

		private RaceDictionary m_RaceDictionary = RaceDictionary.Instance;

		public RaceDictionary RaceDictionary { get { return m_RaceDictionary; } }

		private RaceDescription m_Race;
		private EntityDescription m_Entity;
		private ActionDescription m_Action;

		private Ul m_RaceList;
		private H1 m_EntityRace;
		private EntityUl m_EntityList;

		private EntityDescriptionSection m_EntityDescription;

		private EntityTable m_EntityTable;

		private SearchForm m_SearchForm;
		private Div m_SearchResults;

		private BuildOrderForm m_BuildOrderForm;

		public RaceDescription Race { get { return m_Race; } }
		public EntityDescription Entity { get { return m_Entity; } }
		public ActionDescription Action { get { return m_Action; } }


		public override void Load(System.Xml.XmlNode node, Jayden.Dll.Web.HtmlControlLoader loader)
		{
			base.Load(node, loader);

			m_RaceList = GetElementByServerId<Ul>("raceList");
			foreach (RaceDescription race in RaceDictionary.Races)
			{
				Li li = m_RaceList.AddLi();
				A a = li.AddA(null, "?raceId=" + race.Id);
				a.AddImg(race.Name, "/Images/" + race.Id + ".png").Title = race.Name;
			}

			m_EntityList = GetElementByServerId<EntityUl>("entityList", true);
			m_EntityTable = GetElementByServerId<EntityTable>("entityTable", true);
			m_EntityRace = GetElementByServerId<H1>("entityRace");
			m_BuildOrderForm = GetElementByServerId<BuildOrderForm>("buildOrderForm", true);
			m_EntityDescription = GetElementByServerId<EntityDescriptionSection>("entityDescription", true);
			m_SearchForm = GetElementByServerId<SearchForm>("searchForm");
			m_SearchResults = GetElementByServerId<Div>("searchResults", true);
		}

		public override void ProcessCssRequest(Jayden.Dll.Web.HttpHandlerContext context)
		{
			base.ProcessCssRequest(context);

			context.Css.NewElement("body").AddProperty("background-position", "center").AddProperty("background-repeat","no-repeat");
			context.Css.NewElement("body.zerg").AddProperty("background-image", "url(/Images/ZergIcon.png)");
			context.Css.NewElement("body.protoss").AddProperty("background-image", "url(/Images/ProtossIcon.png)");
			context.Css.NewElement("body.terran").AddProperty("background-image", "url(/Images/TerranIcon.png)");
			context.Css.NewElement(".icons li").AddProperty("display", "inline");
			context.Css.NewElement(".icons li img").AddProperty("width", "36px").AddProperty("height", "36px");
			context.Css.NewElement("table img").AddProperty("width", "24px").AddProperty("height", "24px");
			context.Css.NewElement("td", "th").AddProperty("background-color", "#fff");
			context.Css.NewElement("#" + m_EntityTable.Id + " tr:hover td").AddProperty("background-color", "#ccc");
		}

		public override void ProcessJsonRequest(Jayden.Dll.Web.HttpHandlerContext context)
		{
			SearchForm.SearchCommandHandler searchHandler = context.HandlerManager.GetHandler<SearchForm.SearchCommandHandler>();
			searchHandler.Search += new SearchForm.OnSearch(Search);
			base.ProcessJsonRequest(context);
		}

		public override void ProcessHtmlRequest(Jayden.Dll.Web.HttpHandlerContext context)
		{
			SearchForm.SearchCommandHandler searchHandler = context.HandlerManager.GetHandler<SearchForm.SearchCommandHandler>();
			searchHandler.Search += new SearchForm.OnSearch(Search);
			m_EntityList.ServerRender = false;
			m_BuildOrderForm.ServerRender = false;
			m_EntityDescription.ServerRender = false;
			m_EntityRace.ServerRender = false;
			m_EntityTable.ServerRender = false;
			string raceId = context.Uri["raceId"];
			string entityId = context.Uri["entityId"];
			if (!string.IsNullOrWhiteSpace(entityId))
			{
				m_Entity = RaceDictionary.GetEntity(entityId);
				if (m_Entity != null)
				{
					m_EntityDescription.ServerRender = true;
					m_Race = m_Entity.Race;
					raceId = m_Race.Id;

					Head.Title.InnerText = "Sc2 - " + m_Race.Name + " - " + m_Entity.Name;
				}
			}
			if (!string.IsNullOrWhiteSpace(raceId))
			{
				if(m_Race == null)
					m_Race = RaceDictionary[raceId];


				if (m_Race != null)
				{
					m_BuildOrderForm.ServerRender = true;
					m_EntityTable.ServerRender = true;
					Body.Class = m_Race.Id.ToLowerInvariant();
					m_EntityList.ServerRender = true;
					m_EntityTable.AddHeaders();

					if(m_Entity == null)
						Head.Title.InnerText = "Sc2 - " + m_Race.Name;

					List<EntityDescription> entities = new List<EntityDescription>(m_Race.Entities);
					entities.Sort(delegate(EntityDescription e1, EntityDescription e2) { return e1.Level.CompareTo(e2.Level); });

					m_EntityList.Set(entities);
					m_EntityTable.Set(entities);
				}
			}
			base.ProcessHtmlRequest(context);
		}

		public override void ProcessJsRequest(Jayden.Dll.Web.HttpHandlerContext context)
		{
			base.ProcessJsRequest(context);

			context.Js[GetType().FullName].AppendAjaxHandler(@"
		if(data." + m_SearchForm.Id + @" === $('#" + m_SearchForm.Term.Id + @"').val()) {
			if(data." + m_SearchResults.Id + @") {
				$('#" + m_SearchResults.Id + @"').html(data." + m_SearchResults.Id + @");
			}
			if(data." + m_EntityList.Id + @") {
				$('#" + m_EntityList.Id + @"').html(data." + m_EntityList.Id + @");
			}
		}
");
		}

		private void Search(Jayden.Dll.Web.HttpHandlerContext context, SearchForm.SearchValues search)
		{
			string raceId = context.Uri["raceId"];
			string entityId = context.Uri["entityId"];
			RaceDescription race = null;
			EntityDescription entity = null;
			if (!string.IsNullOrWhiteSpace(entityId))
			{
				entity = RaceDictionary.GetEntity(entityId);
				if (entity != null)
				{
					race = entity.Race;
					raceId = race.Id;
				}
			}
			List<EntityDescription> matches = new List<EntityDescription>();
			if (!string.IsNullOrWhiteSpace(raceId))
			{
				if (race == null)
					race = RaceDictionary[raceId];
				if (race != null)
				{
					foreach (EntityDescription raceEntity in race.Entities)
					{
						try
						{
							if (Regex.IsMatch(raceEntity.Id, search.Term, RegexOptions.IgnoreCase))
								matches.Add(raceEntity);
						}
						catch (Exception e)
						{
						}
					}
				}
			}
			else
			{
				foreach(RaceDescription descr in RaceDictionary.Races)
					foreach (EntityDescription raceEntity in descr.Entities)
					{
						try
						{
							if (Regex.IsMatch(raceEntity.Id, search.Term, RegexOptions.IgnoreCase))
								matches.Add(raceEntity);
						}
						catch (Exception e)
						{
						}
					}
			}
			m_EntityTable.ServerRender = true;
			m_EntityList.ServerRender = true;
			m_EntityTable.Clear();
			m_EntityList.Clear();
			m_EntityTable.AddHeaders();

			matches.Sort(delegate(EntityDescription e1, EntityDescription e2) { return e1.Level.CompareTo(e2.Level); });
			foreach (EntityDescription raceEntity in matches)
			{
				Li li = m_EntityList.AddLi();
				A a = li.AddA(null, "?entityId=" + raceEntity.Id);
				a.AddImg(raceEntity.Id, "/Images/" + raceEntity.IconId + ".gif").Title = raceEntity.Name;

				m_EntityTable.AddTr(raceEntity);
			}

			if (context.RequestType == HttpRequestType.Json)
			{
				context.Json.Add(m_SearchResults.Id, m_SearchResults.ToInnerHtml(context.Translator));
				context.Json.Add(m_EntityList.Id, m_EntityList.ToInnerHtml(context.Translator));
			}
		}
	}
}
